<template>
  <div>
    <Card dis-hover>
      <h3>
        {{ taskName }}
      </h3>
      <ButtonGroup slot="extra">
        <Button @click="approvalInfo" type="warning" style="background: #EF5350;" :loading="buttonloading"
                v-if="approval">
          <Icon type="ios-bookmark"/>
          审批
        </Button>
        <Button @click="returnTo">
          返回
          <Icon type="ios-arrow-forward"/>
        </Button>
      </ButtonGroup>
    </Card>
    <Row>
      <i-col span="24">
        <Card dis-hover style="margin: 10px;">
          <Spin fix v-if="spinShow">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>Loading</div>
          </Spin>
          <div :style="{height: bodyHeight + 'px', overflowY: 'auto', overflowX: 'hidden', }">
            <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
              <Row :gutter="16">
                <i-col span="24">
                  <FormItem label="审计任务">
                    <Input v-model="adtReport.missionName" type="text" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16">
                <i-col span="24">
                  <FormItem label="被审计单位">
                    <Input v-model="adtReport.auditedOrgName" type="text" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16">
                <i-col span="12">
                  <FormItem label="开始时间">
                    <Input v-model="adtReport.planStart" type="text" readonly/>
                  </FormItem>
                </i-col>
                <i-col span="12">
                  <FormItem label="结束时间">
                    <Input v-model="adtReport.planEnd" type="text" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16">
                <i-col span="12">
                  <FormItem label="审计组长">
                    <Input v-model="adtReport.groupLeaderName" type="text" readonly/>
                  </FormItem>
                </i-col>
                <i-col span="12">
                  <FormItem label="带队">
                    <Input v-model="adtReport.supervisor" type="text" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16">
                <i-col span="24">
                  <FormItem label="概述">
                    <Input v-model="adtReport.reportDesc" type="text" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16">
                <i-col span="24">
                  <FormItem label="审计报告附件">
                    <Upload ref="upload" v-if="ifFile"
                            :before-upload="beforeUpload"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                    <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                      <a @click="downloadFile(adtReport.reportId, item,index)">{{ item.fileName }}</a>
                      <Button type="text" icon="md-trash" @click="remove1(item.id)" v-if="ifFile"
                              style="margin-left: 5px;margin-bottom: 3px"/>
                      <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                    </div>
                  </FormItem>
                </i-col>
              </Row>
              <Divider orientation="left" v-if="approval">操作信息</Divider>
              <Row :gutter="16">
                <i-col span="8" v-if="ifRoute">
                  <FormItem label="审批意见：" prop="route">
                    <Select filterable v-model="formData.route">
                      <Option v-for="item in routeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16" v-if="approval">
                <i-col span="8">
                  <FormItem label="操作人：">
                    <Input v-model="formData.userName" readonly/>
                  </FormItem>
                </i-col>
                <i-col span="8">
                  <FormItem label="操作时间：">
                    <Input v-model="formData.createDateStr" readonly/>
                  </FormItem>
                </i-col>
              </Row>
              <Row :gutter="16" v-if="approval">
                <i-col span="24">
                  <FormItem label="说明：" prop="opinion">
                    <Input type="textarea" v-model="formData.opinion"/>
                  </FormItem>
                </i-col>
              </Row>
            </Form>
          </div>
        </Card>
      </i-col>
    </Row>
  </div>
</template>

<script>
import {Api} from '../../../api'
import {sessionStorage} from '@/common/cacheUtils.js';

export default {
  name: "adtReportForm",
  data() {
    return {
      uploadListVisible: [],
      uploadListPercent: [],
      taskName: '',
      buttonloading: false,
      approval: false,
      spinShow: true,
      taskInfo: {},
      bodyHeight: '',
      formData: {},
      ruleCustom: {
        route: [
          {
            type: 'integer',
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
      },
      routeList: [
        {
          id: 1,
          name: '合格'
        },
        {
          id: 2,
          name: '不合格'
        }
      ],
      ifRoute: false,
      ifFile: false,
      ifReportOpinion: true,
      noReportOpinion: true,
      adtReport: {},
      userInfo: {},
      uploadList: [],
      fileUrl: Api.interestedPartiesUserFile,
    }
  },
  mounted() {
    this.bodyHeight = window.innerHeight - 175;
    this.taskName = this.$route.query.taskName;
    this.taskInfo = this.$route.query;
    this.userInfo = sessionStorage('userId').getObject('userId');
    this.formData = {
      userName: this.userInfo.userName,
      taskId: this.taskInfo.taskId,
      createUserId: this.userInfo.userId,
      createDateStr: this.formatDate(new Date(), 'yyyy-MM-dd'),
      procinstId: this.taskInfo.procinstId,
    };
    if (this.taskInfo.status == 'done' || this.taskInfo.status == 'self') this.approval = false; else this.approval = true;
    this.query();
  },
  methods: {
    approvalInfo() {
      this.$refs['formCustom'].validate((valid) => {
        if (valid) {
          this.buttonloading = true;
          this.$http.get(Api.taskComplete, {
            params: this.formData
          }).then(function (response) {
            if (response.data.status == 200) {
              this.$Message.success({content: '保存成功', duration: 4});
              this.returnTo();
            } else {
              this.$Message.error({content: '保存失败', duration: 4});
            }
            this.buttonloading = false;
          });
        } else {
          this.$Message.error({content: '请填写完整！', duration: 4});
        }
      });
    },
    returnTo() {
      this.$router.go(-1);
    },
    query() {
      this.$http.get(Api.getAdtTwoReport + '/' + this.taskInfo.workId).then(function (response) {
        if (response.data.status == 200) {
          this.adtReport = response.data.data;
          this.$set(this.adtReport, 'planStart', this.adtReport.planStart != undefined ? this.formatDate(new Date(this.adtReport.planStart), 'yyyy-MM-dd') : '');
          this.$set(this.adtReport, 'planEnd', this.adtReport.planEnd != undefined ? this.formatDate(new Date(this.adtReport.planEnd), 'yyyy-MM-dd') : '');
        }
        this.getFiles();
        if (this.approval == true) this.queryFormList();
        this.spinShow = false;
      });
    },
    queryFormList() {
      this.$http.get(Api.getProcinstForm + '/' + this.taskInfo.taskId).then(function (response) {
        if (response.data.formList.length != 0) {
          response.data.formList.map((i) => {
            if (i.id == 'route') this.ifRoute = true;
            else if (i.id == 'file') this.ifFile = true;
            else if (i.id == 'opinion') this.ifReportOpinion = false;
            else if (i.id == 'noOpinion') this.noReportOpinion = false;
          });
        }
        if (response.data.variables != undefined) {
          this.$set(this.formData, 'reportOpinion', response.data.variables['reportOpinion']);
        }
      });
    },
    async getFiles() {
      let url = this.fileUrl + '/' + this.adtReport.reportId + '/files/adtReport'
      await this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data;
          let index = 0;
          this.uploadList.forEach(item => {
            this.uploadListPercent[index] = 0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      })
    },
    downloadFile(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      this.uploadListVisible[index] = true;
      var _this = this;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob);
        aLink.download = file.fileName; //标题
        aLink.click();
        document.body.appendChild(aLink);
      })
    },
    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles();
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.adtReport.reportId + '/files/adtReport';
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功");
          this.getFiles();
        }
      })
      return false;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  }

}
</script>

<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
</style>
